/**
 * 0. Project	: com.dnbns.bodywater 프로젝트
 *
 * 1. FileName	: GraphActivity.java
 * 2. Package	: com.dnbns.bodywater
 * 3. 작성자		: 윤화현
 * 4. 작성일		: 2013. 11. 21. 오전 9:22:45
 * 5. Comment	: 
 */

package com.dnbns.bodywater;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

import com.dnbns.lib.CodeUtil;

public class GraphActivity2 extends Activity {

    private Context mContext;
    private String mBackgroundColor = "#ffffff";
    private String mLabelcolor = "#000000";
    
    private int mYear;
    private int mMonth;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_graph);

		init();
		initTop();
		settingChart();
	}

/**
 ***************************************************************
 * init
 ***************************************************************
 */

	private void init() {
		mContext = this;
		
		Button prev = (Button)findViewById(R.id.prev);
		Button next = (Button)findViewById(R.id.next);

		prev.setOnClickListener(OCL);
		next.setOnClickListener(OCL);

    	Calendar cal = Calendar.getInstance();
    	mYear = cal.get(Calendar.YEAR);
    	mMonth = (cal.get(Calendar.MONTH)+1);

	}
	
	private void initTop(){
		ImageView back = (ImageView)findViewById(R.id.back);
		back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}
	

/**
 ***************************************************************
 * Method
 ***************************************************************
 */

	private void settingChart(){
    	// 각 계열의 제목.
        String[] titles = new String[] { mMonth+"월" };
        
    	//차트값 초기화
		double[] dd = new double[31];
		for(int i=0; i < 31; i++){
			dd[i] = 0;
		}

		//DB에서 차크값 가져오기.
		JSONArray objA = CodeUtil.getInstance(mContext).getQuery("water_graph", ""+mYear, ""+mMonth);

		for(int i=0; i<objA.length(); i++){
			try {
				dd[objA.getJSONObject(i).getInt("day")] += objA.getJSONObject(i).getInt("cup_vol");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		// 각 계열의 값들.
		List<double[]> values = new ArrayList<double[]>();
		values.add(dd);
		
		makeChart(titles, values);
	}
	
	private void makeChart(String[] titles, List<double[]> values){
		
		// 각 계열의 색깔.
		String[] colors = new String[] { "#48b7e8" };

		// renderer 객체 생성.
		XYMultipleSeriesRenderer renderer = buildBarRenderer(colors);
		setChartSettings(renderer, "제목인데 뭘 적지.", "day", "ml", 0.5, 10.5, 0, 3000);

		renderer.getSeriesRendererAt(0).setDisplayChartValues(true);
//		renderer.getSeriesRendererAt(1).setDisplayChartValues(true);
		//표시 간격
		renderer.setXLabels(12);
		renderer.setYLabels(5);
		renderer.setGridColor(Color.BLACK);
		renderer.setShowGridX(true);
		//정렬방향
		renderer.setXLabelsAlign(Align.CENTER);
		renderer.setYLabelsAlign(Align.LEFT);
		renderer.setXLabelsColor(Color.parseColor(mLabelcolor));
		renderer.setYLabelsColor(0, Color.parseColor(mLabelcolor));
		//스크롤여부
		renderer.setPanEnabled(true, false);
		renderer.setPanLimits(new double[] {0, 32, 0, 3000});
		//춤여부
		renderer.setZoomEnabled(false, false);
		renderer.setZoomRate(1.1f);
		renderer.setBarSpacing(0.3f);
		
		GraphicalView mGraphicalView = ChartFactory.getBarChartView(mContext, buildBarDataset(titles, values), renderer, Type.DEFAULT);
		LinearLayout dynamicLayout = (LinearLayout)findViewById(R.id.graph_layout);

		// 리니어 레이아웃에 차트뷰 추가( 폭, 높이 가득차게 )
		dynamicLayout.addView(mGraphicalView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		
	}
	
    //Dataset 정리
	protected XYMultipleSeriesDataset buildBarDataset(String[] titles, List<double[]> values) {
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
		int length = titles.length;
		for (int i = 0; i < length; i++) {
			CategorySeries series = new CategorySeries(titles[i]);
			double[] v = values.get(i);
			int seriesLength = v.length;
			for (int k = 0; k < seriesLength; k++) {
				series.add(v[k]);
			}
			dataset.addSeries(series.toXYSeries());
		}
		return dataset;
	}

    //Renderer 객체 생성및 각 값 지정.
	protected XYMultipleSeriesRenderer buildBarRenderer(String[] colors) {
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		// text사이즈 지정.
		renderer.setAxisTitleTextSize(20);		//X,Y축 제목
		renderer.setChartTitleTextSize(24);		//차트제목
		renderer.setLabelsTextSize(15);
		renderer.setLegendTextSize(15);
		
		// 생성하는 차트 값 지정.
		int length = colors.length;
		for (int i = 0; i < length; i++) {
			SimpleSeriesRenderer r = new SimpleSeriesRenderer();
			r.setColor(Color.parseColor(colors[i]));
			r.setChartValuesTextAlign(Align.RIGHT);
			r.setChartValuesTextSize(18);
			renderer.addSeriesRenderer(r);
		}
		return renderer;
	}

    //차트의 기본적인 셋팅.
	protected void setChartSettings(XYMultipleSeriesRenderer renderer,
			String title, String xTitle, String yTitle, double xMin,
			double xMax, double yMin, double yMax) {
		
		//마진 셋팅
		renderer.setMargins(new int[] {30, 30, 0, 0} );
		//Bg 칼러 셋팅
		renderer.setApplyBackgroundColor(true);
		renderer.setMarginsColor(Color.parseColor(mBackgroundColor));
		renderer.setBackgroundColor(Color.parseColor(mBackgroundColor));
		//제목 셋팅
		renderer.setChartTitle(title);	//차트제목		
		renderer.setXTitle(xTitle);		//X 타이틀
		renderer.setYTitle(yTitle);		//Y 타이틀
		//X, Y축 값 셋팅
		renderer.setXAxisMin(xMin);
		renderer.setXAxisMax(xMax);
		renderer.setYAxisMin(yMin);
		renderer.setYAxisMax(yMax);
		//Text 칼러 셋팅
		renderer.setAxesColor(Color.parseColor(mLabelcolor));
		renderer.setLabelsColor(Color.parseColor(mLabelcolor));
	}

/**
 ***************************************************************
 * Event
 ***************************************************************
 */

	private View.OnClickListener OCL = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.prev:
				
				break;
			case R.id.next:
				
				break;
			}
		}
	};

	
}
